package com.cy.detectsys.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

public class IPRangeConverter {

    public static void main(String[] args) {
        String cidrNotation = "20.140.64.96/28";
        try {
            String[] ipRange = convertCidrToRange(cidrNotation);
            System.out.println("Start IP: " + ipRange[0]);
            System.out.println("End IP: " + ipRange[1]);
        } catch (UnknownHostException e) {
            System.err.println("Error converting IP address: " + e.getMessage());
        }
    }

    public static String[] convertCidrToRange(String cidr) throws UnknownHostException {
        String[] parts = cidr.split("/");
        String ipStr = parts[0];
        int prefixLength = Integer.parseInt(parts[1]);

        // 将IP地址转换为整数
        long ipInt = ipToLong(ipStr);

        // 计算子网掩码
        long subnetMask = ~(long)(Math.pow(2, 32 - prefixLength) - 1);

        // 计算网络地址
        long networkAddress = ipInt & subnetMask;

        // 计算广播地址
        long broadcastAddress = networkAddress | (subnetMask ^ 0xFFFFFFFFL);

        // 将网络地址和广播地址转换回点分十进制格式
        String startIp = longToIp(networkAddress);
        String endIp = longToIp(broadcastAddress);

        return new String[] { startIp, endIp };
    }

    private static long ipToLong(String ip) throws UnknownHostException {
        InetAddress address = InetAddress.getByName(ip);
        byte[] bytes = address.getAddress();
        long ipLong = ByteBuffer.wrap(bytes).getInt() & 0xFFFFFFFFL;
        return ipLong;
    }

    private static String longToIp(long ipLong) {
        String[] octets = new String[4];
        for (int i = 0; i < 4; i++) {
            octets[3 - i] = Long.toString(ipLong & 0xFF);
            ipLong >>= 8;
        }
        return String.join(".", octets);
    }
}